package fafmessenger_server.boundary;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import fafmessenger_server.control.Controller;

public class Listener extends Thread {

	private Controller controller;
	
	public Listener(Controller c) {
		controller = c;
	}
	
	public void run() {
		ServerSocket welcomeSocket = null;
		
		try {
			welcomeSocket = new ServerSocket(2222);
			GUI.writeLineToConsole("Listening on port 2222.");
			
			while(true) {
				Socket connectionSocket = welcomeSocket.accept();
				GUI.writeLineToConsole("Connection accepted from " + connectionSocket.getInetAddress());
				
				try {
					ClientConnection clientConnection = new ClientConnection(controller, connectionSocket);
					clientConnection.start();
					
				} catch (IOException e) {
					connectionSocket.close();
					e.printStackTrace();
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (welcomeSocket != null) {
				try {
					welcomeSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
}